import { defineStore } from "pinia";
import { store } from "@/store";

export const useDictStore = defineStore("dict", () => {
  type dictType = {
    key: string;
    value: OptionType[];
  }[];

  // state 变量
  const dict: dictType = reactive(new Array());
  // actions
  /**
   * 获取字典类型
   * @param _key
   * @returns
   */
  function getDict(_key: string) {
    if (_key == null || _key == "") {
      return null;
    }
    try {
      for (let i = 0; i < dict.length; i++) {
        if (dict[i].key == _key) {
          return dict[i].value;
        }
      }
    } catch (e) {
      return null;
    }
  }

  /**
   * 设置字典
   * @param _key
   * @param value
   */
  function setDict(_key: string, value: OptionType[]) {
    if (_key !== null || _key == "") {
      dict.push({
        key: _key,
        value: value,
      });
    }
  }

  /**
   * 删除字典
   * @param _key
   * @returns
   */
  function removeDict(_key: string) {
    var bln = false;
    try {
      for (let i = 0; i < dict.length; i++) {
        if (dict[i].key == _key) {
          dict.splice(i, 1);
          return true;
        }
      }
    } catch (e) {
      bln = false;
    }
    return bln;
  }

  /**
   * 清空字典
   */
  function cleanDict() {
    dict.splice(0, dict.length);
  }

  /**
   * 初始字典
   */
  function initDict() {}

  return {
    dict,
    getDict,
    setDict,
    removeDict,
    cleanDict,
  };
});

// 非setup
export function useDictStoreHook() {
  return useDictStore(store);
}
